<template>
  <div class="my">
    <NavBar title="" :showPlaceholder="false">
      <template #right>
        <div class="title_background__more" @click="handleClickMore">
          <Icon name="sangediandian1" size="18" color="#fff" />
          <div class="EditExit" :class="{ 'active': isEditExitActive }">
            <div class="EditExit__item" @click="handleClickEditPersonalInformation">修改个人信息</div>
            <div class="EditExit__item" @click="handleClickLogout">退出登录</div>
          </div>
        </div>
      </template>
    </NavBar>
    <div class="my_title_background"
      :style="{ height: backgroundHeight + 'px', transform: `scale(${backgroundScale})`, '--scale': backgroundScale }">
      <img class="background" src="http://43.138.15.137:8080/assets/img/281578538336_.pic_hd.e816ad71.jpg" alt="">
    </div>
    <div class="profile" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"
      @mousedown="handleMouseDown" @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp"
      :style="{ transform: `translate(0px, 0px) scale(1) translateZ(0px)` }">
      <div class="avatar_wrap">
        <img class="avatar" :src="userInfo?.userAvatar" alt="">
      </div>
      <div class="name_wrap">
        <div class="name">
          {{ userInfo?.userNickname }}
        </div>
        <div class="subname">
          抖音号: {{ userInfo?.userId }}
        </div>
      </div>
      <div class="desc_wrap">
        <div class="desc">{{ userInfo?.userDesc }}</div>
        <div class="desc_wrap_info">
          <div class="gender">
            <Icon :name="userInfo?.userGender === '男' ? 'nanxing' : 'women-line'" size="12"
              :color="userInfo?.userGender === '男' ? '#448fe0' : '#ec407a'" />
            <span>{{ userInfo?.userGender === '男' ? '男' : '女' }}</span>
          </div>
          <div class="desc_wrap_info_age">
            <span>{{ userInfo?.userAge }}岁</span>
          </div>
          <!-- 地址 -->
          <div class="desc_wrap_info_address">
            <span>{{ userInfo?.userAddress }}</span>
          </div>
        </div>

      </div>
      <div class="num_wrap">
        <div class="li">{{ likeNum }}获赞</div>
        <div class="li" @click="handleClickFollow">{{ followNum }}关注</div>
        <div class="li" @click="handleClickFans">{{ fansNum }}粉丝</div>
      </div>
      <Tab v-model="currentIndex" @Tabchange="handleTabChange">
        <TabItem :label="`作品${workNum}`">
          <div class="tab_list">
            <div class="tab_list_item" v-for="item in workData" :key="item.Video.videoId"
              @click="() => handleVideoClick(item, workData)">
              <img :src="item.Video.videoCover" @error="(e) => { e.target.src = defaultCoverImage }" alt="">
              <div class="tab_list_item__delete">
                <Icon name="icon" size="16" color="#fff" />
              </div>
              <div class="tab_list_item__like">
                <Icon name="xin-2" size="14" :color="item.WSLCNum.likeNum > 0 ? 'red' : '#ccc'" />
                <span>{{ item.WSLCNum.likeNum }}</span>
              </div>
            </div>
          </div>
          <!-- 暂时没有更多作品 -->
          <div class="commit_list_wrap_more">暂无更多作品</div>
        </TabItem>
        <TabItem :label="`动态${workNum}`">
          <div class="follow">
            <div class="follow_item" v-for="item in dynamicData" :key="item.Video.videoId">
              <div class="follow_item_top">
                <img class="follow_item_top__avatar"
                  src="http://43.138.15.137:3000/assets/avatar/5a544ec7-0301-46b6-96df-0a033fd0cf1c.png" alt="">
                <span class="follow_item_top__username">@{{ item.Video.userNickname }}</span>
              </div>
              <div class="follow_item_desc">{{ item.Video.videoDesc }}</div>
              <div class="follow_item_video">
                <CustomVideo :showProgress="false" :src="item.Video.videoPath">
                </CustomVideo>
              </div>
              <div class="follow_item_bar">
                <div class="follow_item_bar_item">
                  <Icon name="xin-2" :color="item.WSLCNum.likeNum > 0 ? 'red' : '#ccc'" size="18" />
                  <span>{{ item.WSLCNum.likeNum }}</span>
                </div>
                <div class="follow_item_bar_item">
                  <Icon name="pinglun" color="#fff" size="18" />
                  <span>{{ item.WSLCNum.commentNum }}</span>
                </div>
                <div class="follow_item_bar_item">
                  <Icon name="a-fenxiangweifenxiang" color="#fff" size="16" />
                  <span>{{ item.WSLCNum.shareNum }}</span>
                </div>
              </div>
              <div class="follow_item_time">2025-9-28</div>
            </div>
          </div>
        </TabItem>
        <TabItem :label="`喜欢${userlikeNum}`">
          <div class="tab_list">
            <div class="tab_list_item" v-for="item in likeData" :key="item.Video.videoId"
              @click="() => handleVideoClick(item, likeData)">
              <img :src="item.Video.videoCover" alt="">
              <div class="tab_list_item__like">
                <Icon name="aixin" size="14" color="#fff" />
                <span>{{ item.WSLCNum.likeNum }}</span>
              </div>
            </div>
          </div>
          <!-- 暂时没有更多喜欢 -->
          <div class="commit_list_wrap_more">暂无更多喜欢</div>
        </TabItem>
      </Tab>

    </div>
    <!-- 视频播放页 -->
    <!-- 从左到右过渡出现 -->
    <transition name="fade-in-right">
      <VideoPlaybackPage v-if="isShowVideoPlaybackPage" v-model="isShowVideoPlaybackPage" :data="videoPlaybackData">
      </VideoPlaybackPage>
    </transition>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import Tab from '@/components/Common/Tabs/index.vue'
import TabItem from '@/components/Common/TabItem/index.vue'
import CustomVideo from '@/components/Common/CustomVideo/index.vue'


// 点击右上角显示退出和修改个人信息弹窗
const isEditExitActive = ref(false)
const handleClickMore = (e) => {
  e.stopPropagation()
  isEditExitActive.value = !isEditExitActive.value
}
// 关闭弹窗的函数

const closeEditExit = () => isEditExitActive.value = false
// 全局点击处理
const handleGlobalClick = (e) => {
  // 判断点击的是否是 .EditExit 或其子元素
  const editExitEl = document.querySelector('.EditExit')
  if (editExitEl && !editExitEl.contains(e.target)) {
    closeEditExit()
  }
}
// 点击修改个人信息
import { useRouter } from 'vue-router'
const router = useRouter()
const handleClickEditPersonalInformation = () => {
  closeEditExit()
  router.push({ name: 'EditPersonalInformation' })
}

// 获取我的页面个人用户信息
import { getMyInfoAPI, logoutAPI } from '@/api/my'
import { useMyUserInfoStore } from '@/stores/MyuserInfo'
const myUserInfoStore = useMyUserInfoStore()

const userInfo = ref({})
const getMyInfo = async () => {
  try {
    const res = await getMyInfoAPI()
    // res.data.userAvatar = 'http://43.138.15.137:3000' + res.data.userAvatar
    res.data.userAvatar = 'http://43.138.15.137:3000' + res.data.userAvatar + '?t=' + new Date().getTime();
    // 赋值给 userInfo
    userInfo.value = res.data
    console.log('获取我的页面个人用户信息成功:', res.data)

    // 保存到状态管理
    myUserInfoStore.setUserInfo(res.data)

  } catch (error) {
    console.log(error)
  }


}
onMounted(() => {
  getMyInfo()
})










const currentIndex = ref(0)

// 拖拽相关状态
const backgroundHeight = ref(150) // 初始高度
const backgroundScale = ref(1) // 添加缩放比例变量
const isDragging = ref(false)
const startY = ref(0)
const currentY = ref(0)
const dragThreshold = 5 // 判断是拖拽还是点击的阈值
const scrollThreshold = 50 // 判断是否在顶部的阈值
let initialScrollTop = 0 // 记录初始滚动位置

// 触摸事件处理
const handleTouchStart = (e) => {
  startY.value = e.touches[0].clientY
  isDragging.value = false
  initialScrollTop = window.pageYOffset || document.documentElement.scrollTop
}

const handleTouchMove = (e) => {
  currentY.value = e.touches[0].clientY
  const deltaY = currentY.value - startY.value
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop

  // 判断是否在页面顶部且向下拖拽
  if (currentScrollTop <= scrollThreshold && deltaY > dragThreshold) {
    // 在顶部且向下拖拽，阻止默认滚动行为，放大背景
    e.preventDefault()
    isDragging.value = true

    // 添加更强的阻尼效果，使变化更慢
    const dampingFactor = Math.sqrt(deltaY / 100) * 0.4 + 0.1 // 减小系数
    const adjustedDeltaY = (deltaY * dampingFactor) / 2 // 除以2使变化更慢
    const newHeight = Math.min(150 + adjustedDeltaY, 300) // 限制最大高度为300px
    backgroundHeight.value = newHeight

    // 计算缩放比例，基于高度变化
    const heightRatio = (newHeight - 150) / 150 // 高度变化比例
    backgroundScale.value = 1 + heightRatio * 0.1 // 缩放比例，高度增加150px时，缩放增加0.1
  }
  // 其他情况不阻止默认行为，允许正常滚动
}

const handleTouchEnd = () => {
  // 松开后恢复原始高度
  backgroundHeight.value = 150
  backgroundScale.value = 1
  isDragging.value = false
}

// 鼠标事件处理（用于桌面端）
const handleMouseDown = (e) => {
  startY.value = e.clientY
  isDragging.value = false
  initialScrollTop = window.pageYOffset || document.documentElement.scrollTop
  document.addEventListener('mousemove', handleDocumentMouseMove)
  document.addEventListener('mouseup', handleDocumentMouseUp)
}

const handleDocumentMouseMove = (e) => {
  currentY.value = e.clientY
  const deltaY = currentY.value - startY.value
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop

  // 判断是否在页面顶部且向下拖拽
  if (currentScrollTop <= scrollThreshold && deltaY > dragThreshold) {
    isDragging.value = true

    // 添加更强的阻尼效果，使变化更慢
    const dampingFactor = Math.sqrt(deltaY / 100) * 0.4 + 0.1 // 减小系数
    const adjustedDeltaY = (deltaY * dampingFactor) / 2 // 除以2使变化更慢
    const newHeight = Math.min(150 + adjustedDeltaY, 250) // 限制最大高度为300px
    backgroundHeight.value = newHeight
  }
}

const handleDocumentMouseUp = () => {
  document.removeEventListener('mousemove', handleDocumentMouseMove)
  document.removeEventListener('mouseup', handleDocumentMouseUp)

  // 松开后恢复原始高度和缩放
  backgroundHeight.value = 150
  backgroundScale.value = 1
  isDragging.value = false
}

// 这些函数是为了兼容模板中的事件绑定
const handleMouseMove = (e) => {
  // 这个函数不会执行，因为实际的事件处理在document上
}

const handleMouseUp = () => {
  // 这个函数不会执行，因为实际的事件处理在document上
}

const handleTabChange = (index) => {
  // 打印当前索引
  console.log(index)
  // 切换到动态页时，请求动态数据
  if (index === 1) {
    getMyDynamic()
  }
  // 切换到喜欢页时，请求我的喜欢数据
  if (index === 2) {
    getMyLike()
  }

}

// 请求动态数据
const dynamicData = ref([])
const getMyDynamic = async () => {
  const res = await getMyDynamicAPI(userId)
  dynamicData.value = res.data
}
// 请求我的喜欢数据
const likeData = ref([])
const getMyLike = async () => {
  const res = await getMyLikeAPI(userId)
  likeData.value = res.data
  console.log('我的喜欢数据:', likeData.value)
}



import { getMyVideoCountAPI, followAPI, fansAPI, likeAPI, likeNumAPI, workNumAPI, getMyDynamicAPI, getMyLikeAPI } from '@/api/my'
import { useUserIDStore } from '@/stores/UserID'

// 获取 store 实例
const defaultCoverImage = 'https://img2.baidu.com/it/u=4022145058,3926562442&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1067'
const workData = ref([])
const userIDStore = useUserIDStore()
const userId = userIDStore.userInfo?.userId
// 获取我的作品
const userAvatar = ref(null)
const getMyVideoCount = async () => {
  const res = await getMyVideoCountAPI(userId)
  userAvatar.value = 'http://43.138.15.137:3000' + res.data[0].Video.userAvatar || defaultCoverImage
  workData.value = res.data
}
// 获取关注数
const followNum = ref(0)
const getFollowNum = async () => {
  const res = await followAPI(userId)
  followNum.value = res.data
}
// 获取粉丝数
const fansNum = ref(0)
const getFansNum = async () => {
  const res = await fansAPI(userId)
  fansNum.value = res.data
}
// 获取获赞数
const likeNum = ref(0)
const getLikeNum = async () => {
  const res = await likeAPI(userId)
  likeNum.value = res.data
}
// 喜欢
const userlikeNum = ref(0)
const getUserLikeNum = async () => {
  const res = await likeNumAPI(userId)
  userlikeNum.value = res.data
}
// 作品数量
const workNum = ref(0)
const getWorkNum = async () => {
  const res = await workNumAPI(userId)
  workNum.value = res.data
}



onMounted(() => {
  getMyVideoCount()
  getFollowNum()
  getFansNum()
  getLikeNum()
  getUserLikeNum()
  getWorkNum()
  // 添加全局点击监听
  document.addEventListener('click', handleGlobalClick)
})
// 组件卸载时移除全局点击监听
onUnmounted(() => {
  document.removeEventListener('click', handleGlobalClick)
})

import { defineAsyncComponent } from 'vue'
const isShowVideoPlaybackPage = ref(false)
const VideoPlaybackPage = defineAsyncComponent(() => import('@/views/home/VideoPlaybackPage/index.vue'))
// 点击视频
// 数据
const videoPlaybackData = ref({
  list: [],
  initialIndex: 0
})
const handleVideoClick = (item, data) => {
  console.log(item, data)
  // 找到当前点击项在 data 中的索引
  const index = data.findIndex(v => v.Video?.videoId === item.Video?.videoId)
  if (index === -1) return

  // 传递整个列表 + 初始索引
  videoPlaybackData.value = {
    list: data,
    initialIndex: index
  }
  isShowVideoPlaybackPage.value = true
}


// 退出登陆
import { useUserStore } from '@/stores/userStatus'
const userStore = useUserStore()

const handleClickLogout = async () => {
  const res = await logoutAPI(userId)
  if (res.code === 200) {
    // 退出登录
    userStore.logout()
    router.push({ name: 'home' })
  }
}

// 跳转关注用户列表
const handleClickFollow = () => {
  router.push({ name: 'Myfollowings' })
}

// 跳转粉丝用户列表
const handleClickFans = () => {
  router.push({ name: 'MyFans' })
}
</script>

<style lang="scss" scoped>
.my {

  // 定位右上角
  .title_background__more {
    width: 32px;
    height: 32px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .EditExit {
      position: absolute;
      top: 100px;
      right: 0;
      width: 80px;
      height: 80px;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 2px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: #fff;
      z-index: 222;
      opacity: 0;
      visibility: hidden;
      transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);

      &.active {
        top: 40px;
        opacity: 1;
        visibility: visible;

      }

      &::after {
        display: block;
        position: absolute;
        top: -15px;
        right: 8px;
        border: 8px solid transparent;
        border-bottom: 8px solid rgba(0, 0, 0, 0.5);
        content: '';
      }

      .EditExit__item {
        flex: 1;
        -webkit-box-flex: 1;
        height: 44px;
        line-height: 44px;
        height: 44px;
        width: 100%;
        text-align: center;
      }

    }
  }
}

.my_title_background {
  width: 100%;
  height: 150px;
  /* 默认高度，会被动态样式覆盖 */
  position: relative;
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  transform-origin: center top;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    /* 确保图片覆盖整个区域 */
  }


}

.profile {
  position: relative;
  width: 100%;
  background: #161622;
  transition-timing-function:
    cubic-bezier(0.165, 0.84, 0.44, 1);
  transition-duration: 0ms;
  transform: translate(0px, 0px) scale(1) translateZ(0px);

  .avatar_wrap {
    position: absolute;
    left: 10px;
    top: -15px;
    border-radius: 50%;
    padding: 5px;
    width: 80px;
    height: 80px;
    background: #161622;

    img {
      border-radius: 50%;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .name_wrap {
    position: relative;
    margin: 0 10px;
    padding: 80px 10px 10px;
    border-bottom: 1px solid rgba(41, 40, 37, 0.8);

    .name {
      color: #fff;
      font-size: 18px;
    }

    .subname {
      margin-top: 5px;
      color: #fff;
      font-size: 12px;
    }
  }

  .desc_wrap {
    margin: 10px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    gap: 15px;

    .desc_wrap_info {
      display: flex;
      gap: 5px;
      align-items: center;

      .gender {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 2px 8px;
        border-radius: 5px;
        background: rgba(67, 51, 63, 0.7);
        font-size: 10px;
        max-width: 50px;
        color: #8b8c96;
        white-space: nowrap;
      }

      .desc_wrap_info_age {
        font-size: 12px;
      }

      .desc_wrap_info_address {
        font-size: 12px;
      }


    }

    .desc {
      color: #8b8c96;
      font-size: 12px;
    }


  }

  .num_wrap {
    margin: 10px;
    width: 200px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    color: #fff;

    .li {
      font-size: 14px;
    }
  }

  .tab_list {
    display: flex;
    flex-wrap: wrap;

    .tab_list_item {
      position: relative;
      width: 33.33%;
      height: 160px;
      border: 1px solid #000;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .tab_list_item__delete {
        position: absolute;
        top: 0;
        right: 2px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .tab_list_item__like {
        position: absolute;
        bottom: 2px;
        left: 6px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: #fff;
        gap: 2px;
      }
    }
  }

  .commit_list_wrap_more {
    text-align: center;
    font-size: 12px;
    color: #65676e;
    margin: 14px 0;
  }

  .follow {
    background-color: #161622;
    padding-bottom: 48px;

    .follow_item {
      width: 98%;
      margin: 10px auto 0;
      display: flex;
      flex-direction: column;
      gap: 10px;
      border-bottom: 1px solid #252425;
      padding: 5px;

      .follow_item_top {
        display: flex;
        align-items: center;
        gap: 5px;

        .follow_item_top__avatar {
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }

        .follow_item_top__username {
          font-size: 14px;
          color: #fff;
        }
      }

      .follow_item_desc {
        font-size: 14px;
        color: #fff;
      }

      .follow_item_video {
        width: 250px;
        height: 350px;
      }

      .follow_item_bar {
        display: flex;
        gap: 10px;

        .follow_item_bar_item {
          display: flex;
          align-items: center;
          gap: 5px;

          font-size: 14px;
          color: #fff;
        }
      }

      .follow_item_time {
        font-size: 12px;
        color: #fff;
      }
    }
  }
}

// 从左到右过渡出现
.fade-in-right-enter-active,
.fade-in-right-leave-active {
  transition: all 0.3s ease-in-out;
}

.fade-in-right-enter-from,
.fade-in-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
</style>